import React, { useEffect, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import styles from './Deposit.module.css';
import axios from '../../axios';

type PaymentStatus = 'success' | 'pending' | 'failed' | null;

interface AlipayTradeQueryResponse {
  alipay_trade_query_response?: {
    trade_status: string;
    total_amount?: string;
  };
}

export default function DepositResult() {
  const navigate = useNavigate();
  const location = useLocation();
  const [loading, setLoading] = useState<boolean>(true);
  const [paymentStatus, setPaymentStatus] = useState<PaymentStatus>(null);
  const [paymentAmount, setPaymentAmount] = useState<number>(0);
  const [orderId, setOrderId] = useState<string>('');

  useEffect(() => {
    const query = new URLSearchParams(location.search);
    const outTradeNo = query.get('out_trade_no');
    
    if (outTradeNo) {
      setOrderId(outTradeNo);
      queryPaymentResult(outTradeNo);
    } else {
      setLoading(false);
      setPaymentStatus('failed');
    }
  }, [location]);

  const queryPaymentResult = async (orderNo: string) => {
    try {
      setLoading(true);
      const response = await axios.get<{
        code: number;
        data: AlipayTradeQueryResponse;
      }>(`/api/alipay/query?orderId=${orderNo}`);
      
      if (response.data.code === 200) {
        const result = response.data.data;
        if (result?.alipay_trade_query_response) {
          const tradeStatus = result.alipay_trade_query_response.trade_status;
          const amount = result.alipay_trade_query_response.total_amount || '0';
          
          setPaymentAmount(parseFloat(amount));
          
          if (tradeStatus === 'TRADE_SUCCESS' || tradeStatus === 'TRADE_FINISHED') {
            setPaymentStatus('success');
          } else if (tradeStatus === 'WAIT_BUYER_PAY') {
            setPaymentStatus('pending');
          } else {
            setPaymentStatus('failed');
          }
        } else {
          setPaymentStatus('failed');
        }
      } else {
        setPaymentStatus('failed');
      }
    } catch (error) {
      console.error('查询支付结果失败', error);
      setPaymentStatus('failed');
    } finally {
      setLoading(false);
    }
  };

  const handleRetry = () => {
    navigate('/my/deposit');
  };

  const handleBackToHome = () => {
    navigate('/my');
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.backButton} onClick={() => navigate(-1)} />
        <h1 className={styles.title}>支付结果</h1>
        <div className={styles.spacer}></div>
      </div>

      <div className={styles.card}>
        <div className={styles.resultContainer}>
          {loading ? (
            <div className={styles.resultDesc}>正在查询支付结果...</div>
          ) : (
            <>
              <div className={`${styles.resultIcon} ${
                paymentStatus === 'success' 
                  ? styles.resultSuccess 
                  : paymentStatus === 'pending' 
                    ? styles.resultPending 
                    : styles.resultFailed
              }`}>
                {paymentStatus === 'success' 
                  ? '✓' 
                  : paymentStatus === 'pending' 
                    ? '⏳' 
                    : '✗'}
              </div>
              
              <div className={styles.resultTitle}>
                {paymentStatus === 'success' 
                  ? '支付成功' 
                  : paymentStatus === 'pending' 
                    ? '等待支付' 
                    : '支付失败'}
              </div>
              
              <div className={styles.resultDesc}>
                {paymentStatus === 'success' 
                  ? '您的洋币已经成功充值到账户' 
                  : paymentStatus === 'pending' 
                    ? '订单已创建，等待支付完成' 
                    : '支付未完成，请重新尝试'}
              </div>

              {paymentStatus === 'success' && (
                <div className={styles.resultAmount}>
                  <div className={styles.resultAmountLabel}>已充值金额</div>
                  <div className={styles.resultAmountValue}>
                    {paymentAmount} 元 = {paymentAmount * 10} 洋币
                  </div>
                </div>
              )}

              <div className={styles.resultButtons}>
                {paymentStatus === 'success' ? (
                  <button 
                    className={`${styles.resultButton} ${styles.primaryButton}`}
                    onClick={handleBackToHome}
                  >
                    返回我的
                  </button>
                ) : (
                  <>
                    <button 
                      className={`${styles.resultButton} ${styles.secondaryButton}`}
                      onClick={handleBackToHome}
                    >
                      返回我的
                    </button>
                    <button 
                      className={`${styles.resultButton} ${styles.primaryButton}`}
                      onClick={handleRetry}
                    >
                      重新充值
                    </button>
                  </>
                )}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}